<template>
  <div class="mform">
    <div class="back">
      <Back>
        <div class="form-btn">
          <el-button type="primary" @click="save()">保存</el-button>
        </div>
      </Back>
    </div>
    <div class="form-content">
      <div class="form-box" style="width: 60%;">
        <el-form ref="formRef" :model="form" :rules="rules" :label-position="'left'" label-width="auto">
          <el-form-item label="图片" prop="img">
            <el-upload class="avatar-uploader" :action="`${$api}/common/upload/pic`" :headers="{
            token: $pinia.state.value.store.token
          }" :show-file-list="false" :on-success="handleImgSuccess">
              <img v-if="form.img" :src="$imgUrl + form.img" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
              <el-icon v-if="form.img" class="img-close-icon" @click.stop="form.img = ''">
                <CircleClose />
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入名称" clearable />
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input v-model="form.sort" placeholder="请输入排序" clearable />
          </el-form-item>
          <el-form-item label="状态" prop="state">
            <el-radio-group v-model="form.state">
              <el-radio value="1" border>启用</el-radio>
              <el-radio value="2" border>禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>

    </div>
  </div>
</template>
<script setup name="GoodsCateDetail">
const { proxy } = getCurrentInstance()
const formRef = ref();
const tree = ref([]);
const form = reactive({ id: '', name: '', sort: '', state: '1', img: '' });
//验证规则
const rules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
};
//保存
async function save() {
  formRef.value.validate(async (valid) => {
    if (valid) {
      let res = await proxy.$post('GoodsCateSave', form)
      if (res.code === 0) {
        ElMessage({ type: 'success', message: '保存成功' });
        proxy.$bus.emit('back');
      }
    }
  });
}

onMounted(() => {
  // 编辑
  let id = proxy.$route.query.id || null;
  if (id) {
    getDetail(id)
  }
});

async function getDetail(id) {
  let res = await proxy.$post('GoodsCateDetail', {
    id
  }, false)
  if (res.code === 0) {
    Object.assign(form, res.data);
  }
}
const handleImgSuccess = (res) => {
  if (res.code == 0) {
    form.img = res.data.url
  }
}
</script>
<style scoped lang="scss"></style>
